// 应用主类
class ConsumptionApp {
    constructor() {
        this.currentView = 'dashboard';
        this.expenses = [];
        this.categories = [];
        this.charts = {};
        this.editingExpenseId = null;
        
        this.init();
    }

    async init() {
        try {
            console.log('开始初始化应用...');
            await this.loadData();
            console.log('数据加载完成');
            
            this.setupEventListeners();
            console.log('事件监听器设置完成');
            
            this.setupNavigation();
            console.log('导航设置完成');
            
            this.setupModals();
            console.log('模态框设置完成');
            
            this.initCharts();
            console.log('图表初始化完成');
            
            this.updateDashboard();
            this.updateExpensesList();
            this.updateCategoriesList();
            
            // 设置默认日期
            const today = new Date().toISOString().split('T')[0];
            const expenseDateInput = document.getElementById('expense-date');
            if (expenseDateInput) {
                expenseDateInput.value = today;
            }
            
            // 加载保存的接口密钥
            this.loadApiKey();
            
            // 更新每日鼓励语句
            this.updateDailyQuote();
            
            console.log('应用初始化完成');
        } catch (error) {
            console.error('应用初始化失败:', error);
            this.showMessage('应用初始化失败: ' + error.message, 'error');
        }
    }

    // 更新每日鼓励语句
    updateDailyQuote() {
        const quotes = [
            '今天也要加油哦！合理消费，理性理财！',
            '每一笔记录都是对未来的投资！',
            '理财从记账开始，财富从今天积累！',
            '小钱不省，大钱难存。今天记账了吗？',
            '消费有度，生活有序，财富有方！',
            '记录每一分支出，掌控每一份收入！',
            '理性消费，让每一分钱都花得有价值！',
            '今天的节约，就是明天的自由！',
            '财务自由从记账开始，梦想从今天起航！',
            '聪明消费，智慧理财，美好生活！'
        ];
        
        // 根据日期选择固定的鼓励语句，确保同一天显示相同内容
        const today = new Date();
        const dayOfYear = Math.floor((today - new Date(today.getFullYear(), 0, 0)) / 86400000);
        const quoteIndex = dayOfYear % quotes.length;
        
        const quoteElement = document.getElementById('daily-quote');
        if (quoteElement) {
            quoteElement.textContent = quotes[quoteIndex];
        }
    }

    // 数据加载
    async loadData() {
        try {
            this.expenses = await window.electronAPI.getExpenses();
            this.categories = await window.electronAPI.getCategories();
        } catch (error) {
            console.error('加载数据失败:', error);
            this.showMessage('加载数据失败', 'error');
        }
    }

    // 事件监听器设置
    setupEventListeners() {
        try {
            // 新增消费按钮
            const addExpenseBtn = document.getElementById('add-expense-btn');
            if (addExpenseBtn) {
                addExpenseBtn.addEventListener('click', (e) => {
                    console.log('新增消费按钮被点击');
                    console.log('this对象:', this);
                    console.log('openExpenseModal方法:', typeof this.openExpenseModal);
                    e.preventDefault();
                    try {
                        this.openExpenseModal();
                    } catch (error) {
                        console.error('调用openExpenseModal时出错:', error);
                    }
                });
                console.log('新增消费按钮事件绑定成功');
            } else {
                console.error('找不到新增消费按钮元素');
            }

            // 新增分类按钮
            const addCategoryBtn = document.getElementById('add-category-btn');
            if (addCategoryBtn) {
                addCategoryBtn.addEventListener('click', (e) => {
                    console.log('新增分类按钮被点击');
                    e.preventDefault();
                    this.openCategoryModal();
                });
                console.log('新增分类按钮事件绑定成功');
            } else {
                console.error('找不到新增分类按钮元素');
            }

            // 生成报告按钮
            const generateReportBtn = document.getElementById('generate-report-btn');
            if (generateReportBtn) {
                generateReportBtn.addEventListener('click', (e) => {
                    console.log('生成报告按钮被点击');
                    e.preventDefault();
                    this.generateReport();
                });
            }

            // 导出数据按钮
            const exportDataBtn = document.getElementById('export-data-btn');
            if (exportDataBtn) {
                exportDataBtn.addEventListener('click', (e) => {
                    console.log('导出数据按钮被点击');
                    e.preventDefault();
                    this.exportData();
                });
            }

            // 期间过滤器
            const periodFilter = document.getElementById('period-filter');
            if (periodFilter) {
                periodFilter.addEventListener('change', () => {
                    this.updateDashboard();
                });
            }

            // 搜索和过滤
            const searchInput = document.getElementById('search-input');
            if (searchInput) {
                searchInput.addEventListener('input', () => {
                    this.updateExpensesList();
                });
            }

            const categoryFilter = document.getElementById('category-filter');
            if (categoryFilter) {
                categoryFilter.addEventListener('change', () => {
                    this.updateExpensesList();
                });
            }

            const startDate = document.getElementById('start-date');
            if (startDate) {
                startDate.addEventListener('change', () => {
                    this.updateExpensesList();
                });
            }

            const endDate = document.getElementById('end-date');
            if (endDate) {
                endDate.addEventListener('change', () => {
                    this.updateExpensesList();
                });
            }

            // 消费描述输入时的智能建议
            const expenseDescription = document.getElementById('expense-description');
            if (expenseDescription) {
                expenseDescription.addEventListener('input', 
                    this.debounce(() => this.suggestCategory(), 500)
                );
            }

            // 设置相关
            const saveApiKeyBtn = document.getElementById('save-api-key');
            if (saveApiKeyBtn) {
                saveApiKeyBtn.addEventListener('click', () => {
                    this.saveApiKey();
                });
            }

            const clearCacheBtn = document.getElementById('clear-cache-btn');
            if (clearCacheBtn) {
                clearCacheBtn.addEventListener('click', () => {
                    this.clearCache();
                });
            }

            const resetDataBtn = document.getElementById('reset-data-btn');
            if (resetDataBtn) {
                resetDataBtn.addEventListener('click', () => {
                    this.resetData();
                });
            }
        } catch (error) {
            console.error('设置事件监听器时出错:', error);
        }
    }

    // 导航设置
    setupNavigation() {
        try {
            const navLinks = document.querySelectorAll('.nav-link');
            console.log(`找到 ${navLinks.length} 个导航链接`);
            
            navLinks.forEach((link, index) => {
                const view = link.dataset.view;
                console.log(`设置导航链接 ${index + 1}: ${view}`);
                
                link.addEventListener('click', (e) => {
                    console.log(`导航链接被点击: ${view}`);
                    console.log('this对象:', this);
                    console.log('switchView方法:', typeof this.switchView);
                    e.preventDefault();
                    try {
                        this.switchView(view);
                    } catch (error) {
                        console.error('调用switchView时出错:', error);
                    }
                });
            });
            
            if (navLinks.length === 0) {
                console.error('没有找到任何导航链接');
            }
        } catch (error) {
            console.error('设置导航时出错:', error);
        }
    }

    // 视图切换
    switchView(view) {
        try {
            console.log(`切换到视图: ${view}`);
            
            // 更新导航状态
            const navLinks = document.querySelectorAll('.nav-link');
            console.log(`找到 ${navLinks.length} 个导航链接`);
            navLinks.forEach(link => {
                link.classList.remove('active');
            });
            
            const activeNavLink = document.querySelector(`[data-view="${view}"]`);
            if (activeNavLink) {
                activeNavLink.classList.add('active');
                console.log(`激活导航链接: ${view}`);
            } else {
                console.error(`找不到导航链接: ${view}`);
            }

            // 更新视图
            const allViews = document.querySelectorAll('.view');
            console.log(`找到 ${allViews.length} 个视图`);
            allViews.forEach(v => {
                v.classList.remove('active');
            });
            
            const targetView = document.getElementById(`${view}-view`);
            if (targetView) {
                targetView.classList.add('active');
                console.log(`激活视图: ${view}-view`);
            } else {
                console.error(`找不到视图: ${view}-view`);
            }

            // 更新页面标题
            const titles = {
                dashboard: '仪表盘',
                expenses: '消费记录',
                categories: '分类管理',
                reports: '报告分析',
                settings: '设置'
            };
            const pageTitle = document.getElementById('page-title');
            if (pageTitle) {
                pageTitle.textContent = titles[view];
                console.log(`更新页面标题: ${titles[view]}`);
            }

            this.currentView = view;

            // 视图特定的更新
            if (view === 'dashboard') {
                this.updateDashboard();
            } else if (view === 'expenses') {
                this.updateExpensesList();
                this.updateCategoryFilter();
            } else if (view === 'categories') {
                this.updateCategoriesList();
            }
        } catch (error) {
            console.error('视图切换时出错:', error);
        }
    }

    // 模态框设置
    setupModals() {
        // 消费记录模态框
        const expenseModal = document.getElementById('expense-modal');
        const expenseForm = document.getElementById('expense-form');
        const expenseClose = document.getElementById('expense-modal-close');
        const expenseCancel = document.getElementById('expense-cancel');

        expenseClose.addEventListener('click', () => this.closeExpenseModal());
        expenseCancel.addEventListener('click', () => this.closeExpenseModal());
        
        expenseForm.addEventListener('submit', (e) => {
            e.preventDefault();
            this.saveExpense();
        });

        // 分类模态框
        const categoryModal = document.getElementById('category-modal');
        const categoryForm = document.getElementById('category-form');
        const categoryClose = document.getElementById('category-modal-close');
        const categoryCancel = document.getElementById('category-cancel');

        categoryClose.addEventListener('click', () => this.closeCategoryModal());
        categoryCancel.addEventListener('click', () => this.closeCategoryModal());
        
        categoryForm.addEventListener('submit', (e) => {
            e.preventDefault();
            this.saveCategory();
        });

        // 点击模态框外部关闭
        window.addEventListener('click', (e) => {
            if (e.target === expenseModal) {
                this.closeExpenseModal();
            }
            if (e.target === categoryModal) {
                this.closeCategoryModal();
            }
        });
    }

    // 图表初始化
    initCharts() {
        // 分类统计饼图
        const categoryCtx = document.getElementById('category-chart').getContext('2d');
        this.charts.category = new Chart(categoryCtx, {
            type: 'doughnut',
            data: {
                labels: [],
                datasets: [{
                    data: [],
                    backgroundColor: [],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });

        // 消费趋势线图
        const trendCtx = document.getElementById('trend-chart').getContext('2d');
        this.charts.trend = new Chart(trendCtx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [{
                    label: '日消费',
                    data: [],
                    borderColor: '#667eea',
                    backgroundColor: 'rgba(102, 126, 234, 0.1)',
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return '¥' + value.toFixed(2);
                            }
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    }
                }
            }
        });
    }

    // 仪表盘更新
    async updateDashboard() {
        const period = document.getElementById('period-filter').value;
        const filteredExpenses = this.getFilteredExpenses(period);
        
        // 更新统计卡片
        const totalExpense = filteredExpenses.reduce((sum, exp) => sum + exp.amount, 0);
        const totalRecords = filteredExpenses.length;
        const avgExpense = totalRecords > 0 ? totalExpense / totalRecords : 0;
        
        document.getElementById('total-expense').textContent = this.formatCurrency(totalExpense);
        document.getElementById('total-records').textContent = totalRecords;
        document.getElementById('avg-expense').textContent = this.formatCurrency(avgExpense);
        
        // 主要分类
        const categoryStats = this.getCategoryStats(filteredExpenses);
        const topCategory = categoryStats.length > 0 ? categoryStats[0].name : '-';
        document.getElementById('top-category').textContent = topCategory;
        
        // 更新图表
        this.updateCategoryChart(categoryStats);
        this.updateTrendChart(filteredExpenses, period);
        
        // 获取 AI 洞察
        this.getAIInsights(filteredExpenses);
    }

    // 获取过滤后的消费记录
    getFilteredExpenses(period) {
        const now = new Date();
        let startDate;
        
        switch (period) {
            case 'week':
                startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
                break;
            case 'month':
                startDate = new Date(now.getFullYear(), now.getMonth(), 1);
                break;
            case 'year':
                startDate = new Date(now.getFullYear(), 0, 1);
                break;
            default:
                startDate = new Date(0);
        }
        
        return this.expenses.filter(expense => {
            const expenseDate = new Date(expense.date);
            return expenseDate >= startDate && expenseDate <= now;
        });
    }

    // 获取分类统计
    getCategoryStats(expenses) {
        const stats = {};
        
        expenses.forEach(expense => {
            const category = this.categories.find(c => c.id === expense.category_id);
            const categoryName = category ? category.name : '未知';
            const categoryColor = category ? category.color : '#95a5a6';
            
            if (!stats[categoryName]) {
                stats[categoryName] = {
                    name: categoryName,
                    amount: 0,
                    color: categoryColor
                };
            }
            stats[categoryName].amount += expense.amount;
        });
        
        return Object.values(stats).sort((a, b) => b.amount - a.amount);
    }

    // 更新分类图表
    updateCategoryChart(categoryStats) {
        this.charts.category.data.labels = categoryStats.map(stat => stat.name);
        this.charts.category.data.datasets[0].data = categoryStats.map(stat => stat.amount);
        this.charts.category.data.datasets[0].backgroundColor = categoryStats.map(stat => stat.color);
        this.charts.category.update();
    }

    // 更新趋势图表
    updateTrendChart(expenses, period) {
        const trendData = this.getTrendData(expenses, period);
        this.charts.trend.data.labels = trendData.labels;
        this.charts.trend.data.datasets[0].data = trendData.data;
        this.charts.trend.update();
    }

    // 获取趋势数据
    getTrendData(expenses, period) {
        const data = {};
        const labels = [];
        const values = [];
        
        // 根据期间确定分组方式
        expenses.forEach(expense => {
            const date = new Date(expense.date);
            let key;
            
            if (period === 'week') {
                key = date.toISOString().split('T')[0]; // 按天
            } else if (period === 'month') {
                key = date.toISOString().split('T')[0]; // 按天
            } else {
                key = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`; // 按月
            }
            
            if (!data[key]) {
                data[key] = 0;
            }
            data[key] += expense.amount;
        });
        
        // 排序并格式化
        const sortedKeys = Object.keys(data).sort();
        sortedKeys.forEach(key => {
            if (period === 'year') {
                labels.push(key);
            } else {
                const date = new Date(key);
                labels.push(date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' }));
            }
            values.push(data[key]);
        });
        
        return { labels, data: values };
    }

    // 获取 AI 洞察
    async getAIInsights(expenses) {
        const insightsContent = document.getElementById('ai-insights-content');
        insightsContent.innerHTML = '<div class="loading">正在分析消费数据...</div>';
        
        try {
            const insights = await window.electronAPI.analyzeExpenses(expenses);
            
            // 检查返回的数据格式
            if (typeof insights === 'object' && insights.insights && insights.suggestions) {
                // 格式化显示AI洞察结果
                let html = '<div class="ai-insights-result">';
                
                if (insights.insights && insights.insights.length > 0) {
                    html += '<div class="insights-section">';
                    html += '<h4><i class="fas fa-lightbulb"></i> 消费洞察</h4>';
                    html += '<ul>';
                    insights.insights.forEach(insight => {
                        html += `<li>${insight}</li>`;
                    });
                    html += '</ul>';
                    html += '</div>';
                }
                
                if (insights.suggestions && insights.suggestions.length > 0) {
                    html += '<div class="suggestions-section">';
                    html += '<h4><i class="fas fa-star"></i> 优化建议</h4>';
                    html += '<ul>';
                    insights.suggestions.forEach(suggestion => {
                        html += `<li>${suggestion}</li>`;
                    });
                    html += '</ul>';
                    html += '</div>';
                }
                
                html += '</div>';
                insightsContent.innerHTML = html;
            } else {
                // 如果返回的是字符串，直接显示
                insightsContent.innerHTML = insights;
            }
        } catch (error) {
            console.error('获取 AI 洞察失败:', error);
            insightsContent.innerHTML = '<p>暂时无法获取 AI 洞察，请检查网络连接或 API 配置。</p>';
        }
    }

    // 消费记录相关方法
    openExpenseModal(expense = null) {
        try {
            console.log('尝试打开消费记录模态框', expense ? '编辑模式' : '新增模式');
            
            const modal = document.getElementById('expense-modal');
            const title = document.getElementById('expense-modal-title');
            const form = document.getElementById('expense-form');
            
            if (!modal) {
                console.error('找不到expense-modal元素');
                return;
            }
            if (!form) {
                console.error('找不到expense-form元素');
                return;
            }
            if (!title) {
                console.error('找不到expense-modal-title元素');
                return;
            }
            
            if (expense) {
                title.textContent = '编辑消费记录';
                this.editingExpenseId = expense.id;
                
                // 填充表单
                document.getElementById('expense-amount').value = expense.amount;
                document.getElementById('expense-description').value = expense.description;
                document.getElementById('expense-category').value = expense.category_id;
                document.getElementById('expense-date').value = expense.date;
                document.getElementById('expense-payment').value = expense.payment_method || 'cash';
                document.getElementById('expense-notes').value = expense.notes || '';
                console.log('设置编辑模式数据完成');
            } else {
                title.textContent = '新增消费记录';
                this.editingExpenseId = null;
                form.reset();
                
                // 设置默认日期
                const today = new Date().toISOString().split('T')[0];
                document.getElementById('expense-date').value = today;
                console.log('设置新增模式数据完成');
            }
            
            this.updateCategoryOptions();
            // 显示模态框
            modal.style.display = 'block';
            setTimeout(() => {
                modal.classList.add('show');
            }, 10);
            console.log('模态框已显示');
        } catch (error) {
            console.error('打开消费记录模态框时出错:', error);
        }
    }

    closeExpenseModal() {
        const modal = document.getElementById('expense-modal');
        modal.classList.remove('show');
        document.getElementById('category-suggestion').style.display = 'none';
        this.editingExpenseId = null;
        // 等待动画完成后隐藏模态框
        setTimeout(() => {
            modal.style.display = 'none';
        }, 400);
    }

    async saveExpense() {
        const form = document.getElementById('expense-form');
        if (!form.checkValidity()) {
            form.reportValidity();
            return;
        }
        
        const expenseData = {
            amount: parseFloat(document.getElementById('expense-amount').value),
            description: document.getElementById('expense-description').value,
            categoryId: parseInt(document.getElementById('expense-category').value),
            date: document.getElementById('expense-date').value,
            paymentMethod: document.getElementById('expense-payment').value,
            notes: document.getElementById('expense-notes').value
        };
        
        try {
            if (this.editingExpenseId) {
                await window.electronAPI.updateExpense(this.editingExpenseId, expenseData);
                this.showMessage('消费记录已更新', 'success');
            } else {
                await window.electronAPI.addExpense(expenseData);
                this.showMessage('消费记录已添加', 'success');
            }
            
            await this.loadData();
            this.updateDashboard();
            this.updateExpensesList();
            this.closeExpenseModal();
        } catch (error) {
            console.error('保存消费记录失败:', error);
            this.showMessage('保存失败，请重试', 'error');
        }
    }

    async deleteExpense(id) {
        if (!confirm('确定要删除这条消费记录吗？')) {
            return;
        }
        
        try {
            await window.electronAPI.deleteExpense(id);
            await this.loadData();
            this.updateDashboard();
            this.updateExpensesList();
            this.showMessage('消费记录已删除', 'success');
        } catch (error) {
            console.error('删除消费记录失败:', error);
            this.showMessage('删除失败，请重试', 'error');
        }
    }

    // 更新消费记录列表
    updateExpensesList() {
        const tbody = document.getElementById('expenses-tbody');
        const searchTerm = document.getElementById('search-input').value.toLowerCase();
        const categoryFilter = document.getElementById('category-filter').value;
        const startDate = document.getElementById('start-date').value;
        const endDate = document.getElementById('end-date').value;
        
        let filteredExpenses = this.expenses.filter(expense => {
            // 搜索过滤
            if (searchTerm && !expense.description.toLowerCase().includes(searchTerm)) {
                return false;
            }
            
            // 分类过滤
            if (categoryFilter && expense.category_id !== parseInt(categoryFilter)) {
                return false;
            }
            
            // 日期过滤
            if (startDate && expense.date < startDate) {
                return false;
            }
            if (endDate && expense.date > endDate) {
                return false;
            }
            
            return true;
        });
        
        // 按日期降序排序
        filteredExpenses.sort((a, b) => new Date(b.date) - new Date(a.date));
        
        tbody.innerHTML = filteredExpenses.map(expense => {
            const category = this.categories.find(c => c.id === expense.category_id);
            const categoryName = category ? category.name : '未知';
            
            return `
                <tr>
                    <td>${this.formatDate(expense.date)}</td>
                    <td>${expense.description}</td>
                    <td><span class="category-tag" style="background-color: ${category?.color || '#95a5a6'}">${categoryName}</span></td>
                    <td>${this.formatCurrency(expense.amount)}</td>
                    <td>${this.getPaymentMethodText(expense.payment_method)}</td>
                    <td>
                        <div class="expense-actions">
                            <button class="edit-btn" onclick="app.openExpenseModal(${JSON.stringify(expense).replace(/"/g, '&quot;')})">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="delete-btn" onclick="app.deleteExpense(${expense.id})">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </td>
                </tr>
            `;
        }).join('');
    }

    // 分类相关方法
    openCategoryModal() {
        const modal = document.getElementById('category-modal');
        const form = document.getElementById('category-form');
        
        form.reset();
        document.getElementById('category-color').value = '#3498db';
        modal.style.display = 'block';
        // 添加延迟以确保CSS动画正常工作
        setTimeout(() => {
            modal.classList.add('show');
        }, 10);
    }

    closeCategoryModal() {
        const modal = document.getElementById('category-modal');
        modal.classList.remove('show');
        // 等待动画完成后隐藏模态框
        setTimeout(() => {
            modal.style.display = 'none';
        }, 400);
    }

    async saveCategory() {
        const form = document.getElementById('category-form');
        if (!form.checkValidity()) {
            form.reportValidity();
            return;
        }
        
        const categoryData = {
            name: document.getElementById('category-name').value,
            color: document.getElementById('category-color').value,
            icon: document.getElementById('category-icon').value
        };
        
        try {
            await window.electronAPI.addCategory(categoryData);
            await this.loadData();
            this.updateCategoriesList();
            this.updateCategoryOptions();
            this.updateCategoryFilter();
            this.closeCategoryModal();
            this.showMessage('分类已添加', 'success');
        } catch (error) {
            console.error('保存分类失败:', error);
            this.showMessage('保存失败，请重试', 'error');
        }
    }

    async deleteCategory(id) {
        if (!confirm('确定要删除这个分类吗？删除后相关的消费记录将显示为"未知分类"。')) {
            return;
        }
        
        try {
            await window.electronAPI.deleteCategory(id);
            await this.loadData();
            this.updateCategoriesList();
            this.updateCategoryOptions();
            this.updateCategoryFilter();
            this.updateDashboard();
            this.updateExpensesList();
            this.showMessage('分类已删除', 'success');
        } catch (error) {
            console.error('删除分类失败:', error);
            this.showMessage('删除失败，请重试', 'error');
        }
    }

    // 更新分类列表
    updateCategoriesList() {
        const grid = document.getElementById('categories-grid');
        
        grid.innerHTML = this.categories.map(category => `
            <div class="category-card">
                <div class="category-icon" style="background-color: ${category.color}">
                    <i class="fas fa-${category.icon}"></i>
                </div>
                <div class="category-name">${category.name}</div>
                <div class="category-actions">
                    <button class="btn btn-danger" onclick="app.deleteCategory(${category.id})">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        `).join('');
    }

    // 更新分类选项
    updateCategoryOptions() {
        const select = document.getElementById('expense-category');
        select.innerHTML = this.categories.map(category => 
            `<option value="${category.id}">${category.name}</option>`
        ).join('');
    }

    // 更新分类过滤器
    updateCategoryFilter() {
        const select = document.getElementById('category-filter');
        select.innerHTML = '<option value="">所有分类</option>' + 
            this.categories.map(category => 
                `<option value="${category.id}">${category.name}</option>`
            ).join('');
    }

    // 智能相关方法
    async suggestCategory() {
        const description = document.getElementById('expense-description').value;
        if (!description.trim()) {
            document.getElementById('category-suggestion').style.display = 'none';
            return;
        }
        
        try {
            const suggestion = await window.electronAPI.suggestCategory(description);
            if (suggestion) {
                document.getElementById('suggested-category').textContent = suggestion;
                document.getElementById('category-suggestion').style.display = 'block';
                
                // 自动选择建议的分类
                const category = this.categories.find(c => c.name === suggestion);
                if (category) {
                    document.getElementById('expense-category').value = category.id;
                }
            }
        } catch (error) {
            console.error('获取分类建议失败:', error);
        }
    }

    // 生成报告
    async generateReport() {
        const reportOutput = document.getElementById('report-output');
        reportOutput.innerHTML = '<div class="loading">正在生成报告...</div>';
        
        try {
            // 获取统计数据
            const statistics = await window.electronAPI.getStatistics('month');
            
            // 构造报告数据
            const reportData = {
                expenses: this.expenses,
                period: '本月',
                statistics: statistics
            };
            
            const report = await window.electronAPI.generateReport(reportData);
            
            // 将Markdown格式转换为更好的HTML显示
            const formattedReport = this.formatMarkdownReport(report);
            reportOutput.innerHTML = formattedReport;
        } catch (error) {
            console.error('生成报告失败:', error);
            reportOutput.innerHTML = '<p>生成报告失败，请检查网络连接或 API 配置。</p>';
        }
    }

    // 格式化Markdown报告为HTML
    formatMarkdownReport(markdown) {
        let html = markdown;
        
        // 转换标题
        html = html.replace(/####\s*(.+)/g, '<h4 class="report-h4">$1</h4>');
        html = html.replace(/###\s*(.+)/g, '<h3 class="report-h3">$1</h3>');
        html = html.replace(/##\s*(.+)/g, '<h2 class="report-h2">$1</h2>');
        html = html.replace(/#\s*(.+)/g, '<h1 class="report-h1">$1</h1>');
        
        // 转换粗体文本
        html = html.replace(/\*\*(.+?)\*\*/g, '<strong class="report-bold">$1</strong>');
        
        // 转换列表项
        html = html.replace(/^\s*-\s*(.+)$/gm, '<li class="report-li">$1</li>');
        
        // 包装连续的列表项
        html = html.replace(/((<li class="report-li">.+<\/li>\s*)+)/g, '<ul class="report-ul">$1</ul>');
        
        // 转换段落
        html = html.replace(/^(?!<[hul]|<\/[hul]|<li|<strong)(.+)$/gm, '<p class="report-p">$1</p>');
        
        // 清理多余的空行
        html = html.replace(/\n\s*\n/g, '\n');
        
        return `<div class="formatted-report">${html}</div>`;
    }

    // 导出数据
    async exportData() {
        try {
            const csvData = await window.electronAPI.exportToCSV(this.expenses);
            this.showMessage('数据已导出到 CSV 文件', 'success');
        } catch (error) {
            console.error('导出数据失败:', error);
            this.showMessage('导出失败，请重试', 'error');
        }
    }

    // 设置相关方法
    saveApiKey() {
        const apiKey = document.getElementById('api-key').value;
        if (apiKey.trim()) {
            localStorage.setItem('siliconflow_api_key', apiKey);
            this.showMessage('API Key 已保存', 'success');
        } else {
            this.showMessage('请输入有效的 API Key', 'error');
        }
    }

    loadApiKey() {
        const apiKey = localStorage.getItem('siliconflow_api_key');
        if (apiKey) {
            document.getElementById('api-key').value = apiKey;
        }
    }

    clearCache() {
        if (confirm('确定要清除所有缓存吗？')) {
            localStorage.clear();
            this.showMessage('缓存已清除', 'success');
        }
    }

    async resetData() {
        if (confirm('确定要重置所有数据吗？此操作不可恢复！')) {
            try {
                // 这里需要实现重置数据的接口
                // await window.electronAPI.resetAllData();
                this.showMessage('数据重置功能待实现', 'warning');
            } catch (error) {
                console.error('重置数据失败:', error);
                this.showMessage('重置失败，请重试', 'error');
            }
        }
    }

    // 工具方法
    formatCurrency(amount) {
        return new Intl.NumberFormat('zh-CN', {
            style: 'currency',
            currency: 'CNY'
        }).format(amount);
    }

    formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN');
    }

    getPaymentMethodText(method) {
        const methods = {
            cash: '现金',
            card: '银行卡',
            alipay: '支付宝',
            wechat: '微信支付',
            other: '其他'
        };
        return methods[method] || '未知';
    }

    showMessage(text, type = 'info') {
        // 创建消息元素
        const message = document.createElement('div');
        message.className = `message ${type}`;
        message.textContent = text;
        
        // 添加到页面顶部
        document.body.insertBefore(message, document.body.firstChild);
        
        // 3秒后自动移除
        setTimeout(() => {
            if (message.parentNode) {
                message.parentNode.removeChild(message);
            }
        }, 3000);
    }

    // 防抖函数
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }
}

// 初始化应用
let app;
window.addEventListener('DOMContentLoaded', () => {
    app = new ConsumptionApp();
});

// 添加一些样式到页面
const style = document.createElement('style');
style.textContent = `
    .category-tag {
        display: inline-block;
        padding: 4px 8px;
        border-radius: 12px;
        color: white;
        font-size: 12px;
        font-weight: 500;
    }
    
    .expense-actions {
        display: flex;
        gap: 4px;
    }
    
    .expense-actions button {
        padding: 4px 6px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 12px;
        color: white;
    }
    
    .edit-btn {
        background-color: #3498db;
    }
    
    .edit-btn:hover {
        background-color: #2980b9;
    }
    
    .delete-btn {
        background-color: #e74c3c;
    }
    
    .delete-btn:hover {
        background-color: #c0392b;
    }
`;
document.head.appendChild(style);